package io.cloud.tec.project.model;

import io.cloud.tec.project.enums.ResultEnum;
import lombok.Data;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.time.Instant;

@Data
public class Result<T> {
    private Integer code;
    private String message;
    private String detailMessage;
    private T data;
    private Long timestamp = Instant.now().toEpochMilli();

    public Result() {
    }

    public static <T> Result success(T body) {
        Result r = new Result();
        r.code = ResultEnum.SUCCESS.code;
        r.message = ResultEnum.SUCCESS.message;
        r.data = body;
        return r;
    }

    public static <T> Result success(Integer code, String message, T body) {
        Result r = new Result();
        r.code = code;
        r.message = message;
        r.data = body;
        return r;
    }

    public static <T> Result fail(T body) {
        ResultEnum unknown = ResultEnum.UNKNOWN;
        return fail(unknown.code, unknown.message, body, null);
    }

    public static <T> Result fail(String message, Throwable throwable) {
        ResultEnum unknown = ResultEnum.UNKNOWN;
        return fail(unknown.code, message, null, throwable);
    }


    public static <T> Result fail(Integer code, String message, Throwable throwable) {
        ResultEnum unknown = ResultEnum.UNKNOWN;
        return fail(unknown.code, message, null, throwable);
    }

    public static <T> Result fail(Integer code, String message, T body, Throwable throwable) {
        Result r = new Result();
        // 如果code=0 || code = 200，则code改赋值为9999，message改赋值为【未知错误(message)】
        r.code = ResultEnum.isSuccessCode(code) ? ResultEnum.UNKNOWN.code : code;
        r.message = ResultEnum.isSuccessCode(code) ? new StringBuilder(ResultEnum.UNKNOWN.message).append("(").append(code).append("-").append(message).append(")").toString() : message;
        r.detailMessage = ExceptionUtils.getStackTrace(throwable);
        r.data = body;
        return r;
    }
}
